package atguigu.gulimall.seckill.schedule;
import atguigu.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/*
 * 秒杀商品的定时上架功能
 */
@Slf4j
@Service
public class SecKillScheduleTask {
    private final String SECKILL_LOCK="seckill:lock:";
    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;
    @Scheduled(cron = "0 */1 * * * ?")
//    @Async
    //增加分布式锁,防止多台服务器重复上架商品
    public void seckillUploadProduct(){
        RLock lock = redissonClient.getLock(SECKILL_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            log.info("开始上架商品......");
            seckillService.uploadSeckillLast3DaysProduct();
        }finally {
            lock.unlock();
        }
    }
}
